using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class MainMenuManager : MonoBehaviour
{
    [SerializeField, Header("加载进度条的父对象")] private GameObject _loadingBarObject;
    [SerializeField, Header("加载进度条的图像")] private Image _loadingBar;
    [SerializeField, Header("需要隐藏的对象")] private GameObject[] _objectsToHide;

    [Space]
    [SerializeField, Header("主要持久化场景")] private SceneField _persistentGameplay;
    [SerializeField, Header("游戏关卡场景")] private SceneField _levelScene;

    private List<AsyncOperation> _scenesToLoad = new List<AsyncOperation>(); // 存储待加载场景的列表

    private void Awake()
    {
        _loadingBarObject.SetActive(false); // 禁用加载进度条
    }

    //开始游戏
    public void StartGame()
    {
        HideMenu(); 

        _loadingBarObject.SetActive(true); // 启用加载进度条

        // 加载持久化场景和游戏关卡场景，并将它们添加到待加载场景列表中
        _scenesToLoad.Add(SceneManager.LoadSceneAsync(_persistentGameplay));
        _scenesToLoad.Add(SceneManager.LoadSceneAsync(_levelScene, LoadSceneMode.Additive));

        StartCoroutine(ProgressLoadingBar()); // 启动异步加载进度条的协程
    }

    // 隐藏界面
    private void HideMenu()
    {
        for (int i = 0; i < _objectsToHide.Length; i++)
        {
            _objectsToHide[i].SetActive(false); // 隐藏需要隐藏的对象
        }
    }

    //异步加载进度条的协程
    private IEnumerator ProgressLoadingBar()
    {
        float loadProgress = 0f; // 总的加载进度

        for (int i = 0; i < _scenesToLoad.Count; i++)
        {
            while (!_scenesToLoad[i].isDone)
            {
                loadProgress += _scenesToLoad[i].progress; // 累加加载进度
                _loadingBar.fillAmount = loadProgress / _scenesToLoad.Count; // 更新加载进度条的显示
                yield return null; // 等待下一帧
            }           
        }
    }
}
